package com.yunhe.portal.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunhe.common.constant.PortalConstant;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.filter.ServerContextHolder;
import com.yunhe.common.model.ResultObject;
import com.yunhe.common.model.authority.RealStation;
import com.yunhe.common.model.mybatis.PageResult;
import com.yunhe.common.util.StringUtil;
import com.yunhe.portal.client.AuthorityClient;
import com.yunhe.portal.domain.DataBannerInfo;
import com.yunhe.portal.model.*;
import com.yunhe.portal.repository.DataBannerInfoRepository;
import com.yunhe.portal.repository.DataNewsInfoRepository;
import com.yunhe.portal.repository.DataNoticeInfoRepository;
import com.yunhe.portal.service.DataBannerInfoService;
import com.yunhe.portal.util.MyHeaderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: DataBannerInfoServiceImpl
 * @Description:
 * @author: GongDaCheng
 * @Date: 9:56 2021/10/22
 */
@Service
public class DataBannerInfoServiceImpl implements DataBannerInfoService {

    @Autowired
    private DataBannerInfoRepository dataBannerInfoRepository;

    @Autowired
    private MyHeaderUtil myHeaderUtil;

    @Autowired
    private AuthorityClient authorityClient;

    @Autowired
    private DataNewsInfoRepository dataNewsInfoRepository;

    @Autowired
    private DataNoticeInfoRepository dataNoticeInfoRepository;

    @Override
    public int createDataBannerInfo(DataBannerInfo dataBannerInfo) throws ArgumentErrorException {
        Long headerUser = myHeaderUtil.getHeaderUser();
        if(headerUser == null){
            throw new ArgumentErrorException("用户信息已过期，请重新登录！");
        }
        String projectCode = ServerContextHolder.getContext().getProjectCode();
        if(StringUtil.isEmpty(projectCode)){
            throw new ArgumentErrorException("请选择对应项目进行维护新闻！");
        }
        dataBannerInfo.setPublishPerson(headerUser);
        dataBannerInfo.setIsDelete("0");
        dataBannerInfo.setPublishTime(new Date());
        dataBannerInfo.setCreateTime(new Date());
        if (PortalConstant.Top_Type.Top.value().equals(dataBannerInfo.getIsTop())){
            dataBannerInfo.setTopTime(new Date());
        }
        return dataBannerInfoRepository.createDataBannerInfo(dataBannerInfo);
    }

    @Override
    public int deleteDataBannerInfo(Long id) {
        //设置更新时间（删除时间）
        DataBannerInfo dataBannerInfo = dataBannerInfoRepository.searchDataBannerInfoByPrimaryKey(id);
        dataBannerInfo.setUpdateTime(new Date());
        dataBannerInfoRepository.updateDataBannerInfoByPrimaryKey(dataBannerInfo);
        return dataBannerInfoRepository.deleteDataBannerInfoByPrimaryKey(id);
    }

    @Override
    public int updateDataBannerInfo(DataBannerInfo dataBannerInfo) {
        dataBannerInfo.setUpdateTime(new Date());
        return dataBannerInfoRepository.updateDataBannerInfoByPrimaryKey(dataBannerInfo);
    }

    @Override
    public DataBannerInfo findDataBannerInfoById(Long id) {
        return dataBannerInfoRepository.searchDataBannerInfoByPrimaryKey(id);
    }

    @Override
    public void setTop(Long id) throws ArgumentErrorException {
        Long headerUser = myHeaderUtil.getHeaderUser();
        if(headerUser == null){
            throw new ArgumentErrorException("用户信息已过期，请重新登录！");
        }
        DataBannerInfo banner = dataBannerInfoRepository.searchDataBannerInfoByPrimaryKey(id);
        banner.setIsTop(PortalConstant.Top_Type.Top.value());
        banner.setUpdateTime(new Date());
        banner.setTopTime(new Date());
        dataBannerInfoRepository.updateDataBannerInfoByPrimaryKey(banner);
    }

    @Override
    public PageResult getBannerByConditionWeb(BannerInfoQueryCondition bannerInfoQueryCondition) throws ArgumentErrorException {
        PageResult result = null;
        String projectCode = ServerContextHolder.getContext().getProjectCode();
        if(StringUtil.isEmpty(projectCode)){
            throw new ArgumentErrorException("请选择对应项目进行维护新闻！");
        }
        List<DataBannerInfoVo> dataBannerInfoVos = new ArrayList<>();
        bannerInfoQueryCondition.setStationId(Long.valueOf(projectCode));
        if (PortalConstant.Banner_Type.Station.value().equals(bannerInfoQueryCondition.getBannerType())){
            //园区管理端
            PageHelper.startPage(bannerInfoQueryCondition.getPage(),bannerInfoQueryCondition.getSize());
            dataBannerInfoVos = dataBannerInfoRepository.findStationDataNoticeInfoByCondition(bannerInfoQueryCondition);
        }else if (PortalConstant.Banner_Type.Company.value().equals(bannerInfoQueryCondition.getBannerType())){
            //企业小程序端
            if(CollectionUtils.isEmpty(bannerInfoQueryCondition.getRealStationIds())){
                //查询当前项目下所有真实园区
                List<Long> stationIds = new ArrayList<>();
                ResponseEntity<ResultObject> responseEntity = authorityClient.searchStationAndOfficeByStationId(Long.valueOf(projectCode));
                if (responseEntity != null) {
                    if (responseEntity.getStatusCode().is2xxSuccessful()) {
                        Object results = responseEntity.getBody().getResults();
                        List<RealStation> realStations = JSON.parseArray(JSON.toJSONString(results), RealStation.class);
                        for (RealStation realStation : realStations) {
                            stationIds.add(realStation.getId());
                        }
                    }
                }
                bannerInfoQueryCondition.setRealStationIds(stationIds);
            }
            PageHelper.startPage(bannerInfoQueryCondition.getPage(),bannerInfoQueryCondition.getSize());
            dataBannerInfoVos = dataBannerInfoRepository.findCompanyDataNoticeInfoByCondition(bannerInfoQueryCondition);

        }
        if(!CollectionUtils.isEmpty(dataBannerInfoVos)){
            PageInfo<DataBannerInfoVo> pageInfo = new PageInfo<>(dataBannerInfoVos);
            result = new PageResult(bannerInfoQueryCondition.getPage(),bannerInfoQueryCondition.getSize(), (int) pageInfo.getTotal(),dataBannerInfoVos);
        }

        return result;
    }

    @Override
    public List<DataBannerInfo> findAppBanner(Long stationId) {
        return dataBannerInfoRepository.findAppBanner(stationId);
    }

    @Override
    public List<DataBannerInfo> findWeChatBanner(Long stationId) {
        return dataBannerInfoRepository.findWeChatBanner(stationId);
    }

    @Override
    public List<NewsAndNotice> getNewsAndNoticeByKeyword( String keyword, String type,String noticeType) {
        List<NewsAndNotice> newsAndNoticeList = new ArrayList<>();
        NewsAndNotice newsAndNotice = new NewsAndNotice();
        if ("news".equals(type)){
            newsAndNoticeList = dataNewsInfoRepository.getNewsAsUrl(keyword);
        }
        if ("notice".equals(type)){
            newsAndNoticeList = dataNoticeInfoRepository.getNoticeAsUrl(keyword,noticeType);
        }
        return newsAndNoticeList;
    }
}
